package com.meitianhui.convenitenbuy.module.mine.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseFragment;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.mine.contract.MineContract;
import com.meitianhui.convenitenbuy.module.mine.di.DaggerMineComponent;
import com.meitianhui.convenitenbuy.module.mine.di.MineModule;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerInfo;
import com.meitianhui.convenitenbuy.module.mine.model.UserInfo;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.AddressDefaultEventBean;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.CollectStoreEventBean;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.RecommenderEventBean;
import com.meitianhui.convenitenbuy.module.mine.presenter.MinePresenter;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.AboutUsActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.AccountSecurityActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.CollectionActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.FadeBackActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.MessageDisPitchActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.QRCodeActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.ReceivingAddressActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.RecommenderActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.ShopperGuideActivity;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.UserInfoActivity;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.SettingStoreDialog;
import com.meitianhui.convenitenbuy.widget.dialog.ShareDialog;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/10/30.
 */

public class MineFragment extends BaseFragment implements MineContract.View {
    public static final String Tag = MineFragment.class.getSimpleName();


    @Inject
    MinePresenter mMinePresenter;
    private ImageView mIvMeUserphoto, mIvMeRecommenderArrow;
    private TextView mTvMeNickname, mTvMeRecommender, mTvMeAboutUsVersion;
    private ImageView mIvMeUsergrade;
    private TextView mIvMeUsernumber;
    private ImageView mIvMeQrCode;
    private RelativeLayout mRlMeReceiveaddress;
    private RelativeLayout mRlMeTaobaoMember;
    private RelativeLayout mRlMeRecommender;
    private RelativeLayout mRlMeCollection;
    private RelativeLayout mRlMeBecomeGuide;
    private RelativeLayout mRlMeMessage;
    private RelativeLayout mRlMePasswordGuarentee;
    private RelativeLayout mRlMeShareApplication;
    private RelativeLayout mRlMeUserFadeback;
    private RelativeLayout mRlMeAboutUs;
    private Button mBtnMeLogin;
    private RelativeLayout mRlMeNotify;
    private ImageView mIvMeUserBackground;

    private ConsumerInfo mConsumerInfo;
    private UMImage mUmImage;
    private ShareDialog mShareDialog;
    private TextView mTvMeDefaultAddress;
    private SettingStoreDialog mTipsDialog;
    private boolean isBindRecommenderSuccess = false;


    @Override
    protected int getLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(LayoutInflater inflater) {
        super.initView(inflater);

        DaggerMineComponent.builder().appComponent(App.getInstance().getAppComponent()).mineModule(new MineModule(this)).build().inject(this);
        initId();
        //利用RxUtils防止用户短时间内多次点击
        initRxClick();
        registerPush();
        getUserInfomation();


    }

    @Override
    public void onStart() {
        super.onStart();
    }

    private void registerPush() {

        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_LOGIN_SUCCESS) {
                        getUserInfomation();
                    }
                }
            }
        });

        //接收到修改了默认地址
        Disposable subscribe1 = RxBus.get().toFlowable(AddressDefaultEventBean.class).subscribe(new Consumer<AddressDefaultEventBean>() {
            @Override
            public void accept(AddressDefaultEventBean address) throws Exception {
                mTvMeDefaultAddress.setText(address.address);
            }
        });

        Disposable subscribe2 = RxBus.get().toFlowable(RecommenderEventBean.class).subscribe(new Consumer<RecommenderEventBean>() {
            @Override
            public void accept(RecommenderEventBean recommenderEventBean) throws Exception {
                isBindRecommenderSuccess = true;
                mIvMeRecommenderArrow.setVisibility(View.INVISIBLE);
                mTvMeRecommender.setText(recommenderEventBean.number);
            }
        });
        mCompositeDisposable.add(subscribe);
        mCompositeDisposable.add(subscribe1);
        mCompositeDisposable.add(subscribe2);

    }

   // 用户界面关闭后 minefragment 刷新数据

    @Override
    public void onResume() {
        super.onResume();
        GlideUtils.setUserCircleImage(getActivity(),InfoProvider.getConsumerInfo(App.getInstance()).getHead_pic_path(), mIvMeUserphoto);
        mMinePresenter.imgUrl2Bitmap(InfoProvider.getConsumerInfo(App.getInstance()).getHead_pic_path());
        mTvMeNickname.setText(InfoProvider.getConsumerInfo(App.getInstance()).getNick_name());

    }

    /*
            * 点击事件
            */
    @Override
    public void call(View v) {
        switch (v.getId()) {
            case R.id.rl_me_user_notify:
                JumpUtil.jumpToActivityWithPhoneNumber(mContext, UserInfoActivity.class);
                break;
            case R.id.iv_me_qr_code:
                JumpUtil.jumpToActivityWithPhoneNumber(mContext, QRCodeActivity.class);
                break;
            case R.id.rl_me_password_guarentee:
                JumpUtil.jumpToActivityWithPhoneNumber(mContext, AccountSecurityActivity.class);
                break;
            case R.id.rl_me_share_application:
                if (mUmImage == null)
                    mUmImage = new UMImage(getActivity(), R.mipmap.logo);
                ShareDialog.OnShareClickListener mShareListener = mMinePresenter.shareListener(mUmImage, shareListener);
                mShareDialog = new ShareDialog(getActivity(), mShareListener,  Constants.TYPE_NO_SHOW_WXMINI_SHARE);
                mShareDialog.show();
                break;
            case R.id.rl_me_receiveaddress:
                //收货地址
                Intent rvAddIntent = JumpUtil.getBaseIntent(0, mContext, ReceivingAddressActivity.class);
                startActivity(rvAddIntent);
                break;
            case R.id.btn_me_login:
                //退出登录
                showTipsDialog();
                break;
            case R.id.rl_me_recommender:
                //推荐人
                if (!isBindRecommenderSuccess) {
                    Intent recIntent = JumpUtil.getBaseIntent(0, mContext, RecommenderActivity.class);
                    startActivity(recIntent);
                }
                break;
            case R.id.rl_me_about_us:
                //关于我们
                Intent aboutUsIntent = JumpUtil.getBaseIntent(0, mContext, AboutUsActivity.class);
                startActivity(aboutUsIntent);
                break;
            case R.id.rl_me_user_fadeback:
                //用户反馈
                JumpUtil.jumpToActivityWithPhoneNumber(mContext, FadeBackActivity.class);
                break;
            case R.id.rl_me_collection:
                //收藏门店
                Intent collectionIntent = JumpUtil.getBaseIntent(0, mContext, CollectionActivity.class);
                RxBus.get().post(new CollectStoreEventBean(Constants.COLLECT_FROM_MYfRAGMENT));
                startActivity(collectionIntent);
                break;
            case R.id.rl_me_message:
                //消息界面
                Intent intent = new Intent(mContext, MessageDisPitchActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_me_become_guide:
                //成为导购
                Intent shopperIntent = new Intent(mContext, ShopperGuideActivity.class);
                startActivity(shopperIntent);
                break;
        }
    }

    private void
    showTipsDialog() {
        mTipsDialog = new SettingStoreDialog(getActivity(), R.style.dialog_with_alpha, new SettingStoreDialog.AlertDialogListener() {
            @Override
            public void onConfirmClick() {
                mTipsDialog.dismiss();
                mMinePresenter.logOut();
            }

            @Override
            public void onCancelClick() {
                mTipsDialog.dismiss();
            }
        });
        mTipsDialog.show();
        mTipsDialog.showCancelBtn(true);
        mTipsDialog.setDialogTitle("提示");
        mTipsDialog.setDialogContent("您确定要退出登录");
        mTipsDialog.setConfirmBtnText("确定");
        mTipsDialog.setCancelBtnText("取消");
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            //Toast.makeText(mContext, , Toast.LENGTH_LONG).show();
            TipUtils.showToast(mContext,"成功了",3);
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            TipUtils.showToast(mContext,t.getMessage(),3);
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {

           // Toast.makeText(mContext, "取消了", Toast.LENGTH_LONG).show();
        }
    };


    @Override
    public void showError(String msg) {

    }

    public void getUserInfomation() {
        mMinePresenter.getUserInfo();
    }

    @Override
    public void getUserInfoSuccess(UserInfo userInfo, ConsumerInfo consumerInfo, String consumerAddress) {
        if (userInfo != null) {
            showUserInfo(userInfo, consumerInfo);
        }
        mTvMeDefaultAddress.setText(consumerAddress);
        mTvMeAboutUsVersion.setText("v " + SystemUtils.getVersionName(mContext));
    }

/*    @Override
    public void setUserPhoto(List<StoreImageBean> storeImageBean) {
        GlideUtils.setUserCircleImage(storeImageBean.get(0).getDoc_path(), mIvMeUserphoto);
        mMinePresenter.imgUrl2Bitmap(storeImageBean.get(0).getDoc_path());
    }*/

    @Override
    public void setUserBackground(Bitmap blurBitmap) {
        mIvMeUserBackground.setImageBitmap(blurBitmap);
    }

    @Override
    public void dismissDialog() {
        mShareDialog.dismiss();
    }

    private void showUserInfo(UserInfo userInfo, ConsumerInfo consumerInfo) {
        this.mConsumerInfo = consumerInfo;
        mIvMeUsernumber.setText(userInfo.getMobile());
        if (consumerInfo == null) {
            mTvMeNickname.setText("");
        } else {
            mTvMeNickname.setText(consumerInfo.getNick_name());
            if (!TextUtils.isEmpty(consumerInfo.getReference_mobile())) {
                isBindRecommenderSuccess = true;
                mTvMeRecommender.setText(consumerInfo.getReference_mobile());
                mIvMeRecommenderArrow.setVisibility(View.INVISIBLE);
            }
           // GlideUtils.setUserCircleImage(InfoProvider.getConsumerInfo(App.getInstance()).getHead_pic_path(), mIvMeUserphoto);
            //mMinePresenter.imgUrl2Bitmap(InfoProvider.getConsumerInfo(App.getInstance()).getHead_pic_path());
            //getUserPhoto(mConsumerInfo.getHead_pic_path());
            setUserGrade(mConsumerInfo.getGrade());
        }
    }


    public void setUserGrade(String userGrade) {
        if (!TextUtils.isEmpty(userGrade)) {
            if ("1".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v1);
            } else if ("2".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v2);
            } else if ("3".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v3);
            } else if ("4".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v4);
            } else if ("5".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v5);
            } else if ("6".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v6);
            } else if ("7".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v7);
            } else if ("8".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v8);
            } else if ("9".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v9);
            } else if ("10".equals(userGrade)) {
                mIvMeUsergrade.setBackgroundResource(R.mipmap.me_v10);
            }
        }
    }


    private void initRxClick() {
        RxUtils.bindEvents(mBtnMeLogin, this);
        RxUtils.bindEvents(mRlMeAboutUs, this);
        RxUtils.bindEvents(mRlMeUserFadeback, this);
        RxUtils.bindEvents(mRlMeShareApplication, this);
        RxUtils.bindEvents(mRlMePasswordGuarentee, this);
        RxUtils.bindEvents(mRlMeBecomeGuide, this);
        RxUtils.bindEvents(mRlMeCollection, this);
        RxUtils.bindEvents(mRlMeRecommender, this);
        RxUtils.bindEvents(mRlMeTaobaoMember, this);
        RxUtils.bindEvents(mRlMeReceiveaddress, this);
        RxUtils.bindEvents(mIvMeQrCode, this);
        RxUtils.bindEvents(mRlMeMessage, this);
        RxUtils.bindEvents(mRlMeNotify, this);


    }

    private void initId() {
        mBtnMeLogin = (Button) getViewById(R.id.btn_me_login);
        mRlMeAboutUs = (RelativeLayout) getViewById(R.id.rl_me_about_us);
        mRlMeUserFadeback = (RelativeLayout) getViewById(R.id.rl_me_user_fadeback);
        mRlMeShareApplication = (RelativeLayout) getViewById(R.id.rl_me_share_application);
        mRlMePasswordGuarentee = (RelativeLayout) getViewById(R.id.rl_me_password_guarentee);
        mRlMeMessage = (RelativeLayout) getViewById(R.id.rl_me_message);
        mRlMeBecomeGuide = (RelativeLayout) getViewById(R.id.rl_me_become_guide);
        mRlMeCollection = (RelativeLayout) getViewById(R.id.rl_me_collection);
        mRlMeRecommender = (RelativeLayout) getViewById(R.id.rl_me_recommender);
        mRlMeTaobaoMember = (RelativeLayout) getViewById(R.id.rl_me_taobaoMember);
        mRlMeReceiveaddress = (RelativeLayout) getViewById(R.id.rl_me_receiveaddress);
        mIvMeQrCode = (ImageView) getViewById(R.id.iv_me_qr_code);
        mIvMeUsernumber = (TextView) getViewById(R.id.iv_me_usernumber);
        mIvMeUsergrade = (ImageView) getViewById(R.id.iv_me_usergrade);
        mTvMeNickname = (TextView) getViewById(R.id.tv_me_nickname);
        mIvMeUserphoto = (ImageView) getViewById(R.id.iv_me_userphoto);
        mRlMeNotify = (RelativeLayout) getViewById(R.id.rl_me_user_notify);
        mIvMeUserBackground = (ImageView) getViewById(R.id.iv_me_user_background);
        mTvMeDefaultAddress = (TextView) getViewById(R.id.tv_me_default_address);
        mTvMeRecommender = (TextView) getViewById(R.id.tv_me_recommender);
        mIvMeRecommenderArrow = (ImageView) getViewById(R.id.iv_me_recommender_arrow);
        mTvMeAboutUsVersion = (TextView) getViewById(R.id.tv_me_about_us_version);
    }

}
